/**
 * 门店相关API
 */
const Router = require('koa-router')
const db = require('../db')

const router = new Router({ prefix: '/api/stores' })

// 获取所有门店列表
router.get('/', async (ctx) => {
  try {
    const stores = await db.query('SELECT * FROM v_stores')
    
    // 处理数据格式，符合小程序端需求
    const formattedStores = stores.map(store => ({
      id: store.id,
      name: store.name,
      address: store.address,
      phone: store.phone,
      businessHours: store.business_hours,
      location: {
        latitude: parseFloat(store.latitude),
        longitude: parseFloat(store.longitude)
      }
    }))
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: formattedStores
    }
  } catch (error) {
    console.error('获取门店列表出错:', error)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '服务器错误',
      data: null
    }
  }
})

// 获取门店详情
router.get('/:id', async (ctx) => {
  const { id } = ctx.params
  
  try {
    const [store] = await db.query('SELECT * FROM v_stores WHERE id = ?', [id])
    
    if (!store) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '门店不存在',
        data: null
      }
      return
    }
    
    // 处理数据格式，符合小程序端需求
    const formattedStore = {
      id: store.id,
      name: store.name,
      address: store.address,
      phone: store.phone,
      businessHours: store.business_hours,
      location: {
        latitude: parseFloat(store.latitude),
        longitude: parseFloat(store.longitude)
      }
    }
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: formattedStore
    }
  } catch (error) {
    console.error('获取门店详情出错:', error)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '服务器错误',
      data: null
    }
  }
})

// 创建新门店
router.post('/', async (ctx) => {
  const { name, address, phone, businessHours, location } = ctx.request.body
  
  // 参数验证
  if (!name || !address || !phone || !businessHours || !location) {
    ctx.status = 400
    ctx.body = {
      code: 400,
      message: '缺少必要参数',
      data: null
    }
    return
  }
  
  try {
    // 插入数据库
    const result = await db.query(
      'INSERT INTO stores (name, address, phone, business_hours, latitude, longitude) VALUES (?, ?, ?, ?, ?, ?)',
      [name, address, phone, businessHours, location.latitude, location.longitude]
    )
    
    // 返回创建成功的门店ID
    ctx.status = 201
    ctx.body = {
      code: 0,
      message: '创建门店成功',
      data: {
        id: result.insertId
      }
    }
  } catch (error) {
    console.error('创建门店出错:', error)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '服务器错误',
      data: null
    }
  }
})

// 更新门店信息
router.put('/:id', async (ctx) => {
  const { id } = ctx.params
  const { name, address, phone, businessHours, location, status } = ctx.request.body
  
  // 参数验证
  if (!name && !address && !phone && !businessHours && !location && status === undefined) {
    ctx.status = 400
    ctx.body = {
      code: 400,
      message: '未提供任何更新字段',
      data: null
    }
    return
  }
  
  try {
    // 检查门店是否存在
    const [store] = await db.query('SELECT * FROM stores WHERE id = ?', [id])
    
    if (!store) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '门店不存在',
        data: null
      }
      return
    }
    
    // 构建更新SQL
    let sql = 'UPDATE stores SET '
    const params = []
    const updates = []
    
    if (name) {
      updates.push('name = ?')
      params.push(name)
    }
    
    if (address) {
      updates.push('address = ?')
      params.push(address)
    }
    
    if (phone) {
      updates.push('phone = ?')
      params.push(phone)
    }
    
    if (businessHours) {
      updates.push('business_hours = ?')
      params.push(businessHours)
    }
    
    if (location && location.latitude) {
      updates.push('latitude = ?')
      params.push(location.latitude)
    }
    
    if (location && location.longitude) {
      updates.push('longitude = ?')
      params.push(location.longitude)
    }
    
    if (status !== undefined) {
      updates.push('status = ?')
      params.push(status)
    }
    
    // 添加更新时间
    updates.push('updated_at = NOW()')
    
    // 拼接SQL
    sql += updates.join(', ')
    sql += ' WHERE id = ?'
    params.push(id)
    
    // 执行更新
    await db.query(sql, params)
    
    ctx.body = {
      code: 0,
      message: '更新门店成功',
      data: { id: parseInt(id) }
    }
  } catch (error) {
    console.error('更新门店出错:', error)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '服务器错误',
      data: null
    }
  }
})

// 删除门店
router.delete('/:id', async (ctx) => {
  const { id } = ctx.params
  
  try {
    // 检查门店是否存在
    const [store] = await db.query('SELECT * FROM stores WHERE id = ?', [id])
    
    if (!store) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '门店不存在',
        data: null
      }
      return
    }
    
    // 执行删除操作
    await db.query('DELETE FROM stores WHERE id = ?', [id])
    
    ctx.body = {
      code: 0,
      message: '删除门店成功',
      data: null
    }
  } catch (error) {
    console.error('删除门店出错:', error)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '服务器错误',
      data: null
    }
  }
})

module.exports = router 